package cn.alone.org.controller;

import cn.alone.basic.util.AjaxResult;
import cn.alone.basic.util.PageList;
import cn.alone.org.domain.Employee;
import cn.alone.org.query.EmployeeQuery;
import cn.alone.org.service.IEmployeeService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    /**
     * RequestBody 将前端接收得对象解析位json格式
     * @param employee 新增或修改
     * @return
     * AjxResult:链式编程
     */
    @PostMapping("/save")
    public AjaxResult save(@RequestBody Employee employee){
        try {
            if(employee.getId()==null){
                employeeService.add(employee);
            }else {
                employeeService.update(employee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作失败").setSuccess(false);
        }
    }

    //删除

    /**
     * /{id}直接接收前端传过来的参数
     * @PathVariable取值
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult removeById(@PathVariable("id") Long id){
        try {
            employeeService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }

    }

    /**
     * 根据id查询一条数据
     * @return
     */
    @GetMapping("/{id}")
    public AjaxResult findById(@PathVariable("id") Long id){
        try {
            employeeService.loadById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /**
     * 获取所有数据
     * @return
     */
    @GetMapping("/list")
    public List<Employee> loadAll(){
        return employeeService.loadAll();
    }


    @PostMapping("/page")
    public PageList<Employee> querPage(@RequestBody EmployeeQuery query){
        return employeeService.querpage(query);
    }
}
